/*
 *  Cero Project - Copyright   2006 The Cero Developement Team 
 *  (Michael Laguerre, Camille Roux, Matthieu Segret, Mathieu Sivade) 
 * 
 *  This program is free software; you can redistribute it and/or modify it 
 *  under the terms of the GNU General Public License as published by the Free 
 *  Software Foundation; either version 2 of the License, or (at your option) 
 *  any later version.
 * 
 *  This program is distributed in the hope that it will be useful, but 
 *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 *  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 *  for more details.
 */

package org.ceroproject.games.base;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;

import org.ceroproject.Sorter;
import org.ceroproject.games.Card;


public class ShuffleSorter implements Sorter<Card> {

	/**
	 * Swaps two cards in the list of cards
	 * 
	 * @param i
	 *            the index of the first card to swap
	 * @param j
	 *            the index of the second card to swap
	 */
	private void swap(List<Card> list, int i, int j) {
		Card t = list.get(i);
		list.set(i, list.get(j));
		list.set(j, t);
	}

	/**
	 * This method of shuffling iterates a number of times proportional to the
	 * size of the array, and it guarantees that each element is swapped at
	 * least once
	 * 
	 */
	public List<Card> sort(Collection<Card> data) {
		List<Card> cardslist = new ArrayList<Card>(data);
		int j;
		Random generator = new Random();
		for (int i = 0; i < cardslist.size(); ++i) {
			j = generator.nextInt(cardslist.size());
			swap(cardslist, i, j);
		}
		return cardslist;
	}

}
